import socket
import threading
from ccolor import Colors

# 常见端口列表
COMMON_PORTS = [
    7, 21, 22, 23, 25, 43, 53, 67, 68, 69, 79, 80, 81, 88, 109, 110, 113,
    119, 123, 135, 137, 138, 139, 143, 161, 162, 179, 194, 220, 389, 443,
    445, 465, 513, 520, 546, 547, 554, 563, 631, 636, 991, 993, 995, 1080,
    1194, 1433, 1434, 1494, 1521, 1701, 1723, 1755, 1812, 1813, 1863, 3269,
    3306, 3307, 3389, 3544, 4369, 5060, 5061, 5355, 5432, 5671, 5672, 6379,
    7001, 8080, 8081, 8088, 8443, 8883, 8888, 9443, 9988, 15672, 50389,
    50636, 61613, 61614
]


def scan_port(host, port):
    """扫描单个端口"""
    try:
        tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp.settimeout(1)
        result = tcp.connect_ex((host, port))
        if result == 0:
            print(f"{Colors.GREEN}[+] {host}:{port} 端口开启{Colors.RESET}")
        tcp.close()
    except Exception as e:
        pass


def scan_segment(host, port_start, segment_size=10):
    """扫描端口段"""
    for port in range(port_start, min(port_start + segment_size, 65536)):
        scan_port(host, port)


def full_scan(host, segment_size=10):
    """全端口扫描"""
    print(f"{Colors.YELLOW}[*] 开始全端口扫描: {host}{Colors.RESET}")
    threads = []
    for i in range(0, 65536, segment_size):
        t = threading.Thread(target=scan_segment, args=(host, i, segment_size))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    print(f"{Colors.YELLOW}[*] 全端口扫描完成{Colors.RESET}")


def common_scan(host):
    """常见端口扫描"""
    print(f"{Colors.YELLOW}[*] 开始常见端口扫描: {host}{Colors.RESET}")
    threads = []
    for port in COMMON_PORTS:
        t = threading.Thread(target=scan_port, args=(host, port))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    print(f"{Colors.YELLOW}[*] 常见端口扫描完成{Colors.RESET}")


def port_run(host, scan_type="common", segment_size=10):
    """端口扫描入口函数"""
    if scan_type == "full":
        full_scan(host, segment_size)
    else:
        common_scan(host)